#include "graphpic.h"

GraphPic::GraphPic(GraphModelsList *_model, QWidget *parent) :
    QWidget(parent)
{
    model = _model;
    resize(450, 450);
    transx = width()/2;
    transy = height()/2;
}

GraphPic::~GraphPic() {

}

void GraphPic::paintEvent(QPaintEvent *pe) {
    QPainter painter(this);
    painter.translate(transx, transy);
    painter.setPen(QPen(Qt::black, 3));
    painter.setBrush(Qt::white);
    for (int i = 0; i < model->getGraphModel().getVertexCount(); ++i)
        for (int j = 0; j < model->getGraphModel().getVertexCount(); ++j)
            drawEdge(&painter, i, j);
    drawVertexes(&painter);
}

QSize GraphPic::sizeHint() const {
    QSize size(450, 450);
    return size;
}

void GraphPic::drawVertexes(QPainter *painter) {
    painter->setFont(QFont("Courier New", 16, QFont::Bold));
    for (int i = 0; i < model->getGraphModel().getVertexCount(); ++i) {
        QPointF point(model->getGraphModel().getVertexCoords(i));
        painter->drawEllipse(point, 20.0, 20.0);
        point.setX(point.x() - 5);
        point.setY(point.y() - 10);
        painter->drawStaticText(point, QStaticText(QString("%1").arg(i)));
    }
}

void GraphPic::drawEdge(QPainter *painter, int i, int j) {
    if (model->getGraphModel().getMatrixEl(i, j)) {
        QLineF line(model->getGraphModel().getVertexCoords(i), model->getGraphModel().getVertexCoords(j));
        painter->drawLine(line);
        double point = line.length() ? (line.length() - 20)/line.length() : 0;
        QPointF arrow0(line.pointAt(point));
        QLineF arrow;
        arrow.setP1(arrow0);
        arrow.setLength(20.0);
        arrow.setAngle(line.angle() - 150);
        painter->drawLine(arrow);
        arrow.setAngle(arrow.angle() + 300);
        painter->drawLine(arrow);
    }
}
